﻿using System.IO;
using System.Xml.Serialization;
using UnityEngine;

public class AccountInfo
{
    public SerizlizerDictionary<string, string> accounts;
    //最后登录的账号
    [XmlAttribute]
    public string lastAccount = "";
    //记住密码
    [XmlAttribute]
    public bool rePassword = false;
    //自动登录
    [XmlAttribute]
    public bool autoLogin = false;
    //服务器ID
    [XmlAttribute]
    public int lastServerId = 0;

    public AccountInfo()
    {
        accounts = new SerizlizerDictionary<string, string>();
    }
}

public class AccountMgr
{
    private static AccountMgr instance = new AccountMgr();
    public static AccountMgr Instance { get => instance; }

    public AccountInfo accountInfo;
    string fileName = "Accounts";
    private AccountMgr()
    {
        this.Load();
    }

    public int lastServerId{
        get => accountInfo.lastServerId;
    }

    private void Load()
    {
        this.accountInfo = XmlDataMgr.Instance.LoadData(typeof(AccountInfo), fileName) as AccountInfo;
    }

    private void Save()
    {
        XmlDataMgr.Instance.SaveData(this.accountInfo, fileName);
    }

    public void ClearRecord()
    {
        this.accountInfo.lastServerId = 0;
        this.accountInfo.lastAccount = "";
        this.accountInfo.rePassword = false;
        this.accountInfo.autoLogin = false;
        this.Save();
    }

    public bool IsRePassword()
    {
        return this.accountInfo.rePassword;
    }

    public bool IsAutoLogin()
    {
        return this.accountInfo.autoLogin;
    }

    public string LastAccount()
    {
        return this.accountInfo.lastAccount;
    }

    public string LastPassword()
    {
        string account = this.accountInfo.lastAccount;
        if (account == "")
        {
            return "";
        }
        if (!this.accountInfo.accounts.ContainsKey(account))
        {
            return "";
        }
        return this.accountInfo.accounts[account];
    }

    public bool Register(string account, string password)
    {
        if (this.accountInfo.accounts.ContainsKey(account))
        {
            return false;
        }
        this.accountInfo.accounts.Add(account, password);
        this.Save();
        return true;
    }

    public bool LoginAccount(string account, string password, bool rePassword, bool autoLogin)
    {
        if (!this.accountInfo.accounts.ContainsKey(account))
        {
            return false;
        }

        if (this.accountInfo.accounts[account] != password)
        {
            return false;
        }
        this.accountInfo.lastAccount = account;
        this.accountInfo.rePassword = rePassword;
        this.accountInfo.autoLogin = autoLogin;
        this.Save();
        return true;
    }

    public void LoginServer(int serverId)
    {
        this.accountInfo.lastServerId = serverId;
        this.Save();
    }
}
